{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "906062ff",
   "metadata": {},
   "source": [
    "# 读取DataPattern下的文件\n",
    "\n",
    "注意：所有JPG图像都会被认为是训练集。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e10397f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "\n",
    "from onekey_algo import OnekeyDS as okds\n",
    "from onekey_algo import get_param_in_cwd\n",
    "\n",
    "data_pattern = get_param_in_cwd('data_pattern', os.path.join(okds.ct, 'crop')) \n",
    "patches = []\n",
    "for r, ds, fs in os.walk(data_pattern):\n",
    "    patches.extend([os.path.join(r, p) for p in fs if p.endswith('.jpg')])\n",
    "\n",
    "patches = pd.DataFrame(patches, columns=['fpath'])\n",
    "patches['fname'] = patches['fpath'].map(lambda x: os.path.basename(x))\n",
    "\n",
    "def map2id(x):\n",
    "    x = os.path.basename(x)\n",
    "    *fname_items, w, h, ltx, lty, rbx, rby = x.split('_')\n",
    "    return '_'.join(fname_items)\n",
    "patches['ID'] = patches['fpath'].map(map2id)\n",
    "patches"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20be592e",
   "metadata": {},
   "source": [
    "# 获取划分的数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "066a6b79",
   "metadata": {},
   "outputs": [],
   "source": [
    "label_f = pd.read_csv(get_param_in_cwd('label_file'))\n",
    "label_f['ID'] = label_f['ID'].map(lambda x: str(x))\n",
    "patches = pd.merge(patches, label_f, on='ID', how='inner')\n",
    "patches"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5b66801",
   "metadata": {},
   "source": [
    "# 保存List模式数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8f8a0c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "ugroups = np.unique(patches['group'])\n",
    "for group in ugroups:\n",
    "    group_info = 'train' if group == 'train' else 'val'\n",
    "    patches[patches['group'] == group][['fpath', 'label']].to_csv(os.path.join('split_info', f'{group_info}.txt'), \n",
    "                                                                  index=False, header=False, sep='\\t')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e8f539e2",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
